<script setup lang='ts'>
import type { IAddCategorie } from '@fl/api/anjutong/model/memberpoints-model'
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { addCategories, categories, deleteCategories, editCategories } from '@fl/api/anjutong'

type RowVO = {
    id: string
    name: string
    status: number | string
}

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const btnList = {
    add: '添加类别',
    delete: '删除',
    edit: '编辑',
} as const
const formType = ref()

const centerDialogVisible = ref(false)
const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    border: true,
    columnConfig: {
        resizable: true,
    },
    columns: [
        { field: 'id', title: '品类id' },
        { field: 'name', title: '品类名称' },
        { field: 'status', slots: { default: 'status' }, title: '状态' },
        { slots: { default: 'operation' }, title: '操作', width: 300 },
    ],
    data: [],
    height: 530,
    loading: false,
})

async function findList() {
    gridOptions.loading = true
    try {
        const data = await categories({ page: tablePage.currentPage, size: tablePage.pageSize, sort: 'createTime,desc' })
        gridOptions.loading = false
        tablePage.total = data.total
        gridOptions.data = data.records
    }
    catch (error) {
        gridOptions.loading = false
    }
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}
const rules = {
    name: [
        {
            message: '请输入商品名称',
            required: true,
        },
    ],
    status: [
        {
            message: '请选择状态',
            required: true,
        },
    ],
}
findList()
function getStatus(row: any) {
    return row?.status === 1
}
async function updateCategorie(row: any, isSwitch: boolean) {
    gridOptions.loading = true
    try {
        const options = {
            id: row.id,
            name: row.name,
            status: isSwitch ? (Number(row.status) === 1 ? 2 : 1) : Number(row.status),
        }
        await editCategories(options)
        ElMessage.success('修改成功')
        submitLoading.value = false
        centerDialogVisible.value = false
        findList()
    }
    catch (error) {
        gridOptions.loading = false
    }
}
function resetFormParams() {
    state.value = {
        id: '',
        name: '',
        status: '',
    }
}

const state = ref({
    id: '',
    name: '',
    status: '',
})
const submitLoading = ref(false)

const columns: PlusColumn[] = [
    {
        label: '品类名称',
        prop: 'name',
        valueType: 'copy',
        width: 120,
    },
    {
        label: '品类状态',
        options: [
            {
                label: '启用',
                value: '1',
            },
            {
                label: '停用',
                value: '2',
            },
        ],
        prop: 'status',
        valueType: 'select',
        width: 120,
    },
]
function mySubmit() {
    submitLoading.value = true
    if (formType.value === btnList.edit)
        return updateCategorie(state.value, false)
    if (formType.value === btnList.add) {
        const options = {
            name: state.value.name,
            status: Number(state.value.status),
        }
        return addSubmit(options)
    }
}
async function editRow(row: any) {
    formType.value = btnList.edit
    state.value = {
        id: row.id,
        name: row.name,
        status: String(row.status),
    }
    centerDialogVisible.value = true
}
function addCategory() {
    formType.value = btnList.add
    centerDialogVisible.value = true
}
async function deleteRow(row: any) {
    gridOptions.loading = true
    try {
        await deleteCategories(row.id)
        ElMessage.success('删除成功')
        findList()
    }
    catch (error) {
        gridOptions.loading = false
    }
}
async function addSubmit(options: IAddCategorie) {
    submitLoading.value = true
    try {
        await addCategories(options)
        ElMessage.success('添加成功')
        centerDialogVisible.value = false
        submitLoading.value = false
        findList()
    }
    catch (error) {
        submitLoading.value = false
    }
}
</script>

<template>
    <div class="bg-white p-30">
        <div class="mb-20 flex justify-end">
            <el-button type="primary"
                       @click="addCategory"
            >
                {{ btnList.add }}
            </el-button>
        </div>

        <vxe-grid v-bind="gridOptions">
            <template #operation="{ row }">
                <el-button @click="editRow(row)">
                    {{ btnList.edit }}
                </el-button>

                <el-button @click="deleteRow(row)">
                    {{ btnList.delete }}
                </el-button>
            </template>

            <template #status="{ row }">
                <vxe-switch :model-value="getStatus(row)"
                            @change="updateCategorie(row, true)"
                />
            </template>

            <template #pager>
                <!-- 使用 pager 插槽 -->
                <vxe-pager v-model:current-page="tablePage.currentPage"
                           v-model:page-size="tablePage.pageSize"
                           :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
                           :total="tablePage.total"
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </div>

    <el-dialog v-model="centerDialogVisible"
               :title="formType"
               width="800"
               destroy-on-close
               :close-on-click-modal="false"
               @close="resetFormParams"
    >
        <div>
            <PlusForm v-model="state"
                      :columns="columns"
                      :rules="rules"
                      label-width="120"
                      @submit="mySubmit"
            >
                <template #footer="{ handleSubmit }">
                    <div>
                        <el-button type="primary"
                                   :loading="submitLoading"
                                   @click="handleSubmit"
                        >
                            提交
                        </el-button>

                        <el-button @click="centerDialogVisible = false">
                            关闭
                        </el-button>
                    </div>
                </template>
            </PlusForm>
        </div>
    </el-dialog>
</template>
